<template>
  <div class=" ">

    <div class="filter-container hs-bg-card hs-panel">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px" class="filter-item"
                v-model="listQuery.name"> </el-input>
      <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" v-permission="'admin:add'"
                 style="float:right" @click="handleAdd"
                 type="primary" icon="el-icon-plus" circle>
      </el-button>
      <el-button style="float:right" type="success" icon="el-icon-download"
                 circle @click="handleDownload()">
      </el-button>
    </div>
    <div class="hs-bg-card hs-panel mt-2">
    <el-table :data="list" v-loading.body="listLoading"
              border fit
              highlight-current-row
              style="width: 100%; margin: 10px 0;">
      <el-table-column type="index" width="50" label="序号"> </el-table-column>
      <el-table-column width="100" label="账号" prop="username">
      </el-table-column>
      <el-table-column width="100" label="姓名" prop="name">
      </el-table-column>
      <el-table-column width="200" label="邮箱" prop="email">
      </el-table-column>
      <el-table-column width="110" label="手机" prop="phone">
      </el-table-column>
      <el-table-column width="60" align="center" label="性别" prop="gender">
        <template slot-scope="scope">
            <span> {{scope.row.gender==0 ? "女":"男"}}</span>
          </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="备注" prop="description">
      </el-table-column>
      <el-table-column width="80" align="center" label="状态" >
        <template slot-scope="scope">
          <el-tag> {{scope.row.status==1 ? " 正常":"锁定"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="最后更新" prop="updatedAt">
      </el-table-column>

      <el-table-column align="center" label="操作" fixed="right" width="170">
        <template slot-scope="scope">
          <el-button v-permission="'adminRole:update'" size="small" type="text" @click="handleRole(scope.row)">角色修改
          </el-button>
          <el-button v-permission="'admin:update'" size="small" type="primary" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
          </el-button>
          <el-button v-permission="'admin:delete'" size="small" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)">
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    </div>
    <div v-show="!listLoading && total > 20" class="pagination-container">
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.pageNum"
                     :page-sizes="[20,30,50]"
                     :page-size="listQuery.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[editDialog.type]"
               :visible.sync="editDialog.show">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">

        <el-form-item label="账户" prop="username">
          <el-input v-model="form.username" placeholder="请输入账户" > </el-input>
        </el-form-item>
        <el-form-item label="密码" placeholder="请输入密码" prop="password">
          <el-input v-model="form.password" disabled> </el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 5}"
                    placeholder="请输入内容"
                    v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户的角色(组)"
               :visible.sync="editRoleDialog.show">
      <role-edit
        ref="editRole"
        @cancel="editRoleDialog.show = false"
        @complete="editRoleDialog.show = false"> </role-edit>
    </el-dialog>
  </div>
</template>
<script>
import { page, addObj, delObj, putObj, exportObjs } from 'api/admin/user'
import { downloadUrl } from 'api/admin/file'
const RoleEdit = r => require.ensure([], () => r(require('./components/RoleEdit.vue')), 'group-user-edit')

export default {
  name: 'user',
  components: {
    RoleEdit
  },
  data () {
    return {
      form: {
        username: undefined,
        name: undefined,
        gender: 1,
        password: undefined,
        email: undefined,
        phone: undefined,
        description: undefined,
        status: 1
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名（登录名）', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名（昵称）', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入姓名（昵称）', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      },
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        name: undefined
      },
      userManager_btn_edit: false,
      userManager_btn_del: false,
      userManager_btn_add: false,
      userManager_btn_role: false,
      editDialog: {
        type: undefined,
        show: false
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      editRoleDialog: {
        userid: 0,
        name: '',
        show: false
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter () {
      this.getList().then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleSizeChange (val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleDownload () {
      exportObjs().then(response => {
        let data = response.data
        window.location.href = downloadUrl(data)
      })
    },
    handleRole (row) {
      this.editRoleDialog.show = true
      this.$nextTick(() => {
        this.$refs.editRole.setModel(row)
      })
    },
    handleAdd () {
      this.form.id = 0
      this.form.password = '123456'
      this.editDialog.type = 'create'
      this.editDialog.show = true
    },
    handleUpdate (row) {
      this.form = row
      this.form.password = '******'
      delete this.form.createdAt
      delete this.form.updatedAt
      this.editDialog.type = 'update'
      this.editDialog.show = true
    },
    handleDelete (row) {
      this.$confirm('此操作将永久删除该用户(' + row.username + '), 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(row.id).then(() => {
          this.$message.success('删除成功')
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      })
    },
    submit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id > 0) {
            this.update()
          } else {
            this.add()
          }
        }
      })
    },
    add () {
      addObj(this.form).then(response => {
        let success = parseInt(response.code) === 0
        if (success) {
          this.complete()
        }
      })
    },
    update () {
      this.form.password = undefined
      putObj(this.form.id, this.form).then(response => {
        let success = parseInt(response.code) === 0
        if (success) {
          this.complete()
        }
      })
    },
    cancel () {
      this.editDialog.show = false
      this.$refs['form'].resetFields()
    },
    complete () {
      this.getList()
      this.cancel()
      this.$message.success('操作成功')
    }
  }
}
</script>
